package net.starwifi.duobao;


import net.starwifi.duobao.utils.IDGenerate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;


@Component("appInitListener")
public class AppInitListener implements ServletContextAware, ApplicationListener<ContextRefreshedEvent> {

    /** logger */
    private static final Logger logger = Logger.getLogger(AppInitListener.class.getName());

    /** servletContext */
    private ServletContext servletContext;

    @Resource(name = "freeMarkerConfigurer")
    private FreeMarkerConfigurer freeMarkerConfigurer;

    public static IDGenerate idGenerate=null;

    @Value("${dev}")
    private boolean dev;

    @Value("${serverNode}")
    private int serverNode;




    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
         idGenerate=IDGenerate.getInstance(serverNode);
         logger.info("--------system start--------");
        if(dev) dev();
    }


    /** 开发者环境(模板刷新). */
    public void dev(){
        new Thread() {
            public void run() {
                while (true){
                    try {
                        freeMarkerConfigurer.getConfiguration().clearTemplateCache();
                        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd hh:mm:ss");
                        logger.info("-------------------- clear cache--"+sdf.format(new Date()));
                        sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }









}
